import json
import requests
from Logs.log import log1
from db_sql import insert_db
from utils import copper_url as url, headers, cop
from datetime import datetime
from retrying import retry


@retry(stop_max_attempt_number=3)
def request():
    form_data = {"marketVmid": "40288092327140f601327141c0560001"}
    resp = requests.post(url, headers=headers, data=form_data)
    return json.loads(resp.text)


def parse(resp):
    db_dict = {}
    main_label = {}
    price_list = resp["body"]["priceList"]
    for p in price_list:
        if p["productSortName"] == "1#铜":
            p_index = price_list.index(p)
            main_label = price_list[p_index]
            break
    db_dict["raw_name"] = main_label["productSortName"]
    db_dict["avg_price"] = main_label["avgPrice"]
    db_dict["lower_price"] = main_label["minPrice"]
    db_dict["higher_price"] = main_label["maxPrice"]
    db_dict["change_amount"] = main_label["highsLowsAmount"]
    db_dict["change_range"] = ""
    db_dict["unit"] = main_label["unit"]
    price_date = main_label["publishDate"]
    price_date = datetime.strptime(price_date, '%Y-%m-%d')
    db_dict["price_date"] = price_date.strftime('%Y/%m/%d')
    timestamp = price_date.strftime('%Y%m%d')
    db_dict["id"] = timestamp + cop
    return db_dict


def save(db_dict):
    db_dict["raw_type"] = cop
    db_dict["source"] = "长江现货"
    db_dict["create_time"] = datetime.now().strftime('%Y/%m/%d %H:%M:%S')
    insert_db(db_dict)


def run():
    try:
        resp = request()
        db_dict = parse(resp)
        save(db_dict)
    except Exception as e:
        log1.error(e)
    log1.info("铜END!")


if __name__ == '__main__':
    run()